<!--
 * @Author: levi7754 levi7754@163.com
 * @Date: 2025-05-09 12:03:04
 * @LastEditors: levi7754 levi7754@163.com
 * @LastEditTime: 2025-10-13 11:23:01
 * @FilePath: \ruoyi-mall-uniapp\src\pages\index\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <view>
		<!-- <s-menu-grid :data="menuData" class="ut-home-menu"/> -->
		<view class="ut-chart-wrapper">
			<view class="ut-toggle">
				<view class="ut-segmented-control">
					<text
						class="ut-segmented-text"
						:class="{'ut-segmented-selected': state.selectTime === 'month'}"
						@tap="onSelectTime('month', 'selectTime')"
					>
						Month
					</text>
					<text>/</text>
					<text
						class="ut-segmented-text"
						:class="{'ut-segmented-selected': state.selectTime === 'year'}"
						@tap="onSelectTime('year', 'selectTime')"
					>
						Year
					</text>
				</view>
				<view class="ut-org-toggle">
					<zb-popover
						v-if="accountType !== 'C'"
						placement="bottom-end"
						:options="actions"
						ref="Popover1"
						class="item-popover"
						@select="onSelect"
					>	
						<view style="display: flex; align-items: center; font-weight: 700;">
							{{ state.selectOrg }}
							<uni-icons type="tune" size="24" />
						</view>
					</zb-popover>
				</view>
			</view>
			<!-- 卡片看板 -->
			<view class="ut-board-wrapper">
				<view class="ut-board-sales ut-board-card">
					<view class="ut-sales-text ut-board-text">
						<view>Sales Revenue</view>
					</view>
					<view class="ut-sales-number">
						<text style="font-size: 28rpx;">$</text>
						<text>{{ revenue }}</text>
					</view>
				</view>
				<view class="ut-board-qty ut-board-card">
					<view class="ut-qty-text ut-board-text">
						<view>Sample Customers</view>
					</view>
					<view class="ut-qty-number">{{ sample }}</view>
				</view>
			</view>
			<!-- 图表 -->
			<view
				v-for="chart in charts"
				:key="chart.ref"
				class="charts-box"
				style="background-color: #fff; border-radius: 12rpx; margin-top: 24rpx;"
			>
				<l-echart :ref="e => setChartRef(chart.ref, e)" />
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, computed, watch } from "vue"
import { onLoad, onShow } from '@dcloudio/uni-app';
import { useI18n } from "vue-i18n"
  import dayjs from 'dayjs';
import * as echarts from 'echarts'
import { useStore } from "vuex"
import BigNumber from "bignumber.js";
import { barOptions, barOptions2, pieOption } from "./options";
import { ajax } from "@/http"

const store = useStore()

const chartInstance = ref({})
const chartRef = ref({})
const current = ref(0)
// 账号类型 S: 销售
const accountType = ref(store.state.user.userInfo.accountType)

const state = reactive({
	selectTime: "month",
	selectOrg: accountType === "C" ? "Personal" : "Dept",
	visible: false
})


const account = computed(() => store.state.user.userInfo.userName)

watch(() => account, () => {
	getServerData()
},
{ deep: true }
)


const { t } = useI18n()
const Popover1 = ref(null)


const onSelect = (item) => {
	console.log(".....", item)
	onSelectTime(item.text, 'selectOrg')
	state.selectOrg = item.text
	// Popover1.value.showPop()
}

const actions = [
	{ text: t("title.organization"), selected: true },
	{ text: t("title.personal"), selected: false },
]

const revenue = ref(0) 
const sample = ref(0) 

	const menuData = ref([])

	const setChartRef = (ref, e) => {
		chartRef.value[ref] = e
		console.log(chartRef)
	}

	const getParams = () => {
		return {
			month_year: state.selectTime || "month",
      sale_department_id: store.state.user.saleOrgConfig.departmentId,
      current_user_id: state.selectOrg === "Dept" ? null : store.state.user.userInfo.id,
		}
	}

	const getServerData = () => {
		//模拟从服务器获取数据时的延时
		setTimeout(() => {
			charts.forEach(async chart => {
				chartInstance.value[chart.ref] = await chartRef.value[chart.ref].init(echarts)
				chartInstance.value[chart.ref].showLoading({ lineWidth: 3 })
			})
				
		// 请求服务
			setTimeout(() => {
				const params = getParams()
        const url = "/nature-business/api/sale_order/select-data-report"
				ajax.get(url, params).then(res => {
					console.log(res, chartInstance)
						charts.forEach(chart => {
							const option = setOptions(chart, res)
							chartInstance.value[chart.ref].setOption(option)
							nextTick(() => {
								chartInstance.value[chart.ref].hideLoading()
							})
						})
						revenue.value = new BigNumber(res.sales_revenue || 0).toFormat(2)
						sample.value = new BigNumber(res.sample_customers || 0).toFormat()
					})
			}, 100);
		}, 100);
	}

	const onSelectTime = (type, field) => {
		if (state[field] === type) return
		state[field] = type
		// 请求服务
		const params = getParams()
    const url = "/nature-business/api/sale_order/select-data-report"
    ajax.get(url, params).then(res => {
			charts.forEach(async chart => {
				const option = setOptions(chart, res)
				chartInstance.value[chart.ref].setOption(option)
				chartInstance.value[chart.ref].hideLoading()
			})
			revenue.value = new BigNumber(res.sales_revenue || 0).toFormat(2)
			sample.value = new BigNumber(res.sample_customers || 0).toFormat()
			console.log(revenue)
		})
	}

	const setOptions = (chart, data) => {
		if (chart.ref === "pieRef") {
			const dataList = []
			data[chart.field].forEach(m => {
				if (dataList.length < 5) {
					dataList.push({ name: m.item_code, value: m.quantity })
				}
			})
			return pieOption(dataList)
		} else if (chart.ref === "barRef") {
			const yAxis = data[chart.field].map(m => m.item_code)
			const series = data[chart.field].map(m => m.quantity)
			yAxis.splice(5)
			series.splice(5)
			return barOptions(yAxis, series)
		}
	}

	// field 数值字段
	const charts = [
		{ ref: 'pieRef', option: pieOption, field: "sample_items" },
		{ ref: 'barRef', option: barOptions, field: "best_selling_items" },
		// { ref: 'barRer2', option: barOptions2 },
	]

	onMounted( ()=>{
		// getServerData()
		// 组件能被调用必须是组件的节点已经被渲染到页面上
		console.log("onMounted")
	})
	
	onShow( ()=>{
		// setTimeout(() => {
		// 	getServerData()
		// }, 100);
	})


	onLoad(() => {
		console.log("onLoad")
	});
</script>
<style lang="scss" scoped>
.ut-home-menu {
	width: initial;
	background-color: #fff;
	margin: 24rpx;
	border-radius: 16rpx;
}
.ut-board-wrapper {
	margin-top: 16rpx;
	// padding: 12rpx 0;
	display: flex;
	justify-content: center;
	align-items: center;
	.ut-board-card {
		flex: 1;
		display: flex;
		justify-content: center;
		flex-direction: column;
		background-color: #fff;
		border-radius: 16rpx;
		box-shadow: rgba(0, 0, 0, 0.08) 0px 0px 3px 1px;
	}
	.ut-board-card:first-child {
		flex: 3;
	}
	.ut-board-card:last-child {
		flex: 2;
	}
	.ut-board-text {
		width: 100%;
		padding: 12rpx;
		align-self: flex-start;
		border-bottom: 1px solid #eee;
		box-sizing: border-box;
		font-size: 13px;
	}
	.ut-board-sales {
		margin-right: 12rpx;
		.ut-sales-number {
			font-size: 56rpx;
			font-weight: 700;
			padding: 16rpx;
			text-align: right;
		}
		// .ut-sales-text {
		// 	width: 100%;
		// 	padding: 16rpx;
		// 	align-self: flex-start;
		// 	border-bottom: 1px solid #eee;
		// 	box-sizing: border-box;
		// }
	}
	.ut-board-qty {
		margin-left: 12rpx;
		.ut-qty-number {
			font-size: 60rpx;
			font-weight: 700;
			padding: 16rpx;
			text-align: right;
		}
		.ut-qty-text {

		}
	}

	
}
.ut-chart-wrapper {
	display: flex;
	flex-direction: column;
	padding: 24rpx;
	.ut-toggle {
		display: flex;
		justify-content: space-between;
		background-color: #fff;
		padding: 24rpx 12rpx;
		border-radius: 12rpx;
		.ut-segmented-control {
			.ut-segmented-text {
				padding: 12rpx;
			}
			.ut-segmented-selected {
				font-size: 30rpx;
				font-weight: 700;
			}
		}
		.ut-org-toggle {
			padding-right: 20rpx;
		}
	}
}
</style>